package com.jzo2o.orders.dispatch.strategys;

import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.orders.dispatch.model.dto.ServeProviderDTO;
import com.jzo2o.orders.dispatch.rules.IDispatchRule;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 规则: 距离近者优先
 */
public class DistanceRule extends AbstractProcessRule {

    public DistanceRule(IProcessRule next) {
        super(next);
    }

    //挑选距离最近的服务者列表返回
    public List<ServeProviderDTO> doFilter(List<ServeProviderDTO> serveProviderDTOS) {
        System.out.println("按距离排序");
        if (CollUtils.size(serveProviderDTOS) < 2) {
            return serveProviderDTOS;
        }
        // 2.按照比较器进行排序，排在最前方优先级最高
        serveProviderDTOS = serveProviderDTOS.stream()
                .sorted(Comparator.comparing(ServeProviderDTO::getAcceptanceDistance))
                .collect(Collectors.toList());

        // 3.遍历优先级最高一个数据
        ServeProviderDTO first = CollUtils.getFirst(serveProviderDTOS);

        //获取跟第一个相同级别的
        return serveProviderDTOS.stream()
                .filter(origin -> origin.getAcceptanceDistance().compareTo(first.getAcceptanceDistance()) == 0)
                .collect(Collectors.toList());
    }
}